package com.waiting.nio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Description
 * @Author bjweitingting
 * @Date 2018/10/17
 **/
public class DemoServer extends Thread {
    private ServerSocket serverSocket;

    public int getPort() {
        return serverSocket.getLocalPort();
    }

    @Override
    public void run() {
        try {
            //端口0，表示自动绑定一个空闲端口
            serverSocket = new ServerSocket(0);
            while (true) {
                //调用accept方法，阻塞等待客户端的连接
                Socket socket = serverSocket.accept();
                //接收到一个连接请求，就创建一个线程负责处理
                System.out.println("接收连接");
                RequestHandler requestHandler = new RequestHandler(socket);
                requestHandler.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        DemoServer demoServer = new DemoServer();
        demoServer.start();
        try (Socket client = new Socket(InetAddress.getLocalHost(), demoServer.getPort())) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            bufferedReader.lines().forEach(s -> System.out.println(s));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
